package com.ruoyi.common.core.utils;

import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Map;

public class EncodingConverter {
    public static void convertToUTF8(Object obj) {
        convertToUTF8(obj, new IdentityHashMap<>());
    }

    private static void convertToUTF8(Object obj, Map<Object, Boolean> visited) {
        if (obj == null || visited.containsKey(obj)) {
            return;
        }
        visited.put(obj, true);

        Class<?> clazz = obj.getClass();
        if (clazz.isPrimitive() || clazz == String.class || clazz.isEnum()) {
            return;
        }

        if (obj instanceof Collection) {
            Collection<?> collection = (Collection<?>) obj;
            for (Object item : collection) {
                convertToUTF8(item, visited);
            }
        } else if (clazz.isArray()) {
            int length = java.lang.reflect.Array.getLength(obj);
            for (int i = 0; i < length; i++) {
                Object arrayElement = java.lang.reflect.Array.get(obj, i);
                convertToUTF8(arrayElement, visited);
            }
        } else {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    Object fieldValue = field.get(obj);
                    if (fieldValue == null) {
                        continue;
                    }
                    if (field.getType() == String.class) {
                        byte[] asciiBytes = ((String) fieldValue).getBytes(StandardCharsets.US_ASCII);
                        String utf8Value = new String(asciiBytes, StandardCharsets.UTF_8);
                        field.set(obj, utf8Value);
                    } else {
                        convertToUTF8(fieldValue, visited);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}    